<?php

namespace app\admin\controller;

use think\Controller;

class Message extends AdminController
{
    public function index()
    {
        // 通过接口获得平台发送的消息
        $url = 'http://www.miaozy.cn/news?token=3116b736c0a7e0830d38102d5ee140cc';
        $msg = json_decode(https_request($url),true);
        $msgdata =$msg['data'];
//        dump($msgdata);

        //发送已读状态
        $url = 'http://www.miaozy.cn/news/dostatus?token=3116b736c0a7e0830d38102d5ee140cc';
        https_request($url);
        return view('index',['data'=>$msgdata]);
    }



    public function msg()
    {
        return view();
    }

    public function sendMsg()
    {
        $post = input('post.');
        $post['uid'] = trim($post['uid']);
//        dump($post);

        if(is_null($post['uid']) || is_null($post['msg'])){
            $this->error('请填写完整');
        }
        if(preg_match('/\d{11,}|[^\d,]/',$post['uid'])){
            $this->error('id格式不正确');
        }

        // 将信息插入msg表
        $arr = [];
        $arr['msg'] = $post['msg'];
        $arr['time'] = time();
        //插入并获取mid
        $mid = db('msg')
                ->insertGetId($arr);

        //如果id为0,代表发给所有用户
        $uid = $post['uid'];
        $arr = [];
        $arr['mid'] = $mid;
        $sum = 0;
        if($uid==0){
            $uidlist = db('user')
                ->field('id')
                ->select();
//            dump($uidlist);
            // 将uid,mid插入user_msg表

            foreach ($uidlist as $v){
                $arr['uid'] = $v['id'];
                $sum += db('user_msg')
                        ->insert($arr);
            }

        }else{
            // 发送给指定用户
            $uidlist = explode(',',$uid);
            foreach ($uidlist as $v){
                $arr['uid'] = $v;
                $sum += db('user_msg')
                    ->insert($arr);
            }
        }

        if($sum!=0){
            $this->success('成功发送'.$sum.'条信息','admin/Message/msg',null,1);
        }else{
            $this->error('发送失败');
        }



    }
}
